package com.mvu.banana.domain.server;

import org.apache.log4j.Logger;

import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import java.util.HashMap;
import java.util.Map;

/**
 * Factory for creating EntityManager.
 */
public final class EMF {
  private static EntityManagerFactory emfInstance;
  private static final Logger logger = Logger.getLogger(EMF.class);

  public static final String URL = "javax.persistence.jdbc.url";
  public static final String AUTO = "hibernate.hbm2ddl.auto";

  public static EntityManagerFactory get() {
    if (emfInstance == null) {
      Map<String, Object> configOverrides = new HashMap<String, Object>();
      String url = ServerProperties.get(URL);
      if (url != null) {
        configOverrides.put(URL, url);
        logger.info(URL + "=" + url);
      }
      String auto = ServerProperties.get(AUTO);
      if (auto != null) {
        configOverrides.put(AUTO, auto);
        logger.info(AUTO + "=" + auto);
      }
      emfInstance = Persistence.createEntityManagerFactory(
              ServerProperties.getPersistenceUnit(), configOverrides);
    }
    return emfInstance;
  }

  private EMF() {
    // nothing
  }
}

